package com.tihi.floatview;

import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

import com.tihi.handsuiviewer.App;
import com.tihi.handsuiviewer.R;
import com.tihi.util.AppUtils;
import com.tihi.util.Preferences;

/**
 * 悬浮窗口控制
 * @author duantihi
 *
 * @date 2016-1-30 下午4:28:39
 */
public class FloatViewMgr {
	
	public interface IFloatViewLis {
		void onClick();
	}
	
	private static FloatViewMgr _instance;
	private IFloatViewLis mLis;
	private View mFloatView;
	private TextView status;
	private TextView tipTextView;
	
	private WindowManager mWindowManager;
	private WindowManager.LayoutParams wmParams;
	private boolean isShowing = false;
	
	//触摸位置
	private float mTouchStartX;
	private float mTouchStartY;
	
	private float mTouchRawX;
	private float mTouchRawY;
	
	private float x;
	private float y;
	
	private FloatViewMgr() {
		init();
		_instance = this;
	}
	
	public static FloatViewMgr instance() {
		if(_instance == null) {
			_instance = new FloatViewMgr();
		}
		return _instance;
	}
	
	public void setListener(IFloatViewLis lis) {
		mLis = lis;
	}
	
	private void init() {
		mFloatView = LayoutInflater.from(App.instance()).inflate(R.layout.float_view_layout, null);
		status = (TextView) mFloatView.findViewById(R.id.status);
		tipTextView = (TextView) mFloatView.findViewById(R.id.tipView);
		
		wmParams = new WindowManager.LayoutParams();
		mWindowManager = (WindowManager) App.instance().getSystemService(App.instance().WINDOW_SERVICE);
		
		//设置window type  
		wmParams.type = LayoutParams.TYPE_PHONE;
		//设置图片格式，效果为背景透明 
		wmParams.format = PixelFormat.RGBA_8888;
		//设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
		//悬浮窗口位置：靠右 上下居中
//		wmParams.gravity = Gravity.RIGHT | Gravity.CENTER;
		wmParams.gravity = Gravity.LEFT|Gravity.TOP;
		// 以屏幕左上角为原点，设置x、y初始值，相对于gravity  
		wmParams.x = AppUtils.dip2px(App.instance(), 95);
		wmParams.y = AppUtils.dip2px(App.instance(), 150);
		//悬浮窗口的长宽设置
		wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		
		mFloatView.setOnTouchListener(getOnTouchListener());
	}
	
	private OnTouchListener getOnTouchListener() {
		return new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				//获取相对屏幕的坐标，即以屏幕左上角为原点         
				x = event.getRawX();   
				y = event.getRawY()-50;   //25是系统状态栏的高度
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						//获取相对View的坐标，即以此View左上角为原点
						mTouchStartX =  event.getX();  
						mTouchStartY =  event.getY();
						
						mTouchRawX = event.getRawX();
						mTouchRawY = event.getRawY();
						break;
					case MotionEvent.ACTION_MOVE:                
						updateViewPosition();
						break;
					case MotionEvent.ACTION_UP:
						//根据拖动位置大小判断是拖动还是点击
						if(Math.abs(event.getRawX() - mTouchRawX) < 10 && Math.abs(event.getRawY() - mTouchRawY) < 10) {
							if(mLis != null) {
								mLis.onClick();
							}
//							tipTextView.setVisibility(View.GONE);
						}else {
							updateViewPosition();
						}
						mTouchStartX=mTouchStartY=0;
						break;
				}
				return true;
			}
		};
	}
	
	private void updateViewPosition(){
		//更新浮动窗口位置参数
		wmParams.x=(int)(x - mTouchStartX);
		wmParams.y=(int) (y - mTouchStartY);
		mWindowManager.updateViewLayout(mFloatView, wmParams);
	}
	
	public void show() {
		try {
			mWindowManager.addView(mFloatView, wmParams);
			mFloatView.measure(View.MeasureSpec.makeMeasureSpec(0,  
	                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec  
	                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));  
		} catch (Exception e) {
			e.printStackTrace();
		}
		isShowing = true;
		setStatus("开始");
		//是否显示悬浮窗的提示语
//		if(Preferences.instance().shouldShowFloatTip()) {
//			Preferences.instance().saveFloatTipViewShowCnt();
//			tipTextView.setVisibility(View.VISIBLE);
//		}else {
//			tipTextView.setVisibility(View.GONE);
//		}
	}
	
	public void setStatus(String msg) {
//		status.setText(msg);
		tipTextView.setText(msg);
	}
	
	/**
	 * 设置可点击状态
	 * @param clickable
	 */
	public void setClickEnable(boolean clickable) {
		mFloatView.setEnabled(clickable);
	}
	
	public void dismiss() {
		try {
			mWindowManager.removeView(mFloatView);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		isShowing = false;
	}
	
	public boolean isShowing() {
		return isShowing;
	}

}
